﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;

namespace CatalogImporter.Utils
{
    /// <summary>
    /// The attribute enumerator
    /// </summary>
    public sealed class AttributeEnumerator : IEnumerator<Attribute>
    {
        #region Private members

        /// <summary>
        /// The file stream
        /// </summary>
        private StreamReader streamReader;

        /// <summary>
        /// The current attibute
        /// </summary>
        private Attribute current;

        #endregion

        #region Constructor

        public AttributeEnumerator(String file)
        {
            this.streamReader = new StreamReader(File.OpenRead(file));

            // Discard the first line as it's just an header
            this.streamReader.ReadLine();
        }

        #endregion

        public Attribute Current
        {
            get { return this.current; }
        }

        object System.Collections.IEnumerator.Current
        {
            get { return this.current; }
        }

        public bool MoveNext()
        {
            if (this.streamReader.EndOfStream)
                return false;

            this.current = ParseAttribute(this.streamReader.ReadLine());

            return true;
        }

        public void Reset()
        {
            throw new InvalidOperationException("Operation not supported by this enumerator");
        }

        public void Dispose()
        {
            if (this.streamReader != null)
            {
                this.streamReader.Close();
                this.streamReader.Dispose();
            }

            this.streamReader = null;
        }

        #region Private members

        private Attribute ParseAttribute(String line)
        {
            String[] values = line.Split(new char[] { ';' });

            return new Attribute() {
                Code = values[2],
                Value = values[3],
                Name = new List<LocalizedItem<String>>() {
                    new LocalizedItem<String>() { Language = "it", Value = values[0] },
                    new LocalizedItem<String>() { Language = "en", Value = values[1] }
                }
            };
        }

        #endregion
    }
}
